import * as React from "react";
import propTypes from "prop-types";
import {Spin} from 'antd';
import {BaseComponent} from "fe-lib";
import Routes from "../routes";
import {apiIsSuccess, apiIsLoading, apiIsRealLoading} from "shared/utils/reducerUtil";
import Database from "./Database";
import Tables from "./Tables";
import TableInfo from "./TableInfo";
import "./index.less";

class Component extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {activeDatabase: null, activeTable: null, columns: []};
    this.bind('clickDatabase', 'clickTable');
  }

  componentWillMount() {
    const {dataSources}=this.props;
    if (!apiIsSuccess(dataSources)) {
      this.props.getDataSources();
    }
  }

  clickDatabase(item) {
    this.setState({
      activeDatabase: item,
      activeTable: null,
      columns: [],
    })
  }

  clickTable(activeTable) {
    this.setState({
      activeTable,
      columns: [],
    })
  }

  render() {
    const {dataSources, ajaxStatus}=this.props;
    const {activeDatabase, activeTable, columns}=this.state;
    const loading = apiIsLoading(dataSources) || apiIsRealLoading(ajaxStatus);
    return (
      <Spin spinning={loading}>
        <div className="web-page">
          <div className="web-datasource web-box">
            <Database databases={dataSources.get('data')} activeDatabase={activeDatabase} onClick={this.clickDatabase}/>
            <Tables database={activeDatabase} activeTable={activeTable} onClick={this.clickTable}/>
            <TableInfo columns={columns} tableName={activeTable}/>
          </div>
          <Routes match={this.props.match}/>
        </div>
      </Spin>
    );
  }
}

/** 定义propTypes */
Component.propTypes = {
  key: propTypes.any,
};

export default Component;
